package com.pansoft.newasset.fragment;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.EnvSupportManager;
import com.pansoft.nfc.mifare.Common;
import com.pansoft.nfc.mifare.activity.MifareAddCardActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.BleBlutoothScanActivity;
import com.pansoft.openplanet.activity.NewAssetCardsDetailsActivity;
import com.pansoft.openplanet.activity.NewStackActivity;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.CardBean;
import com.pansoft.openplanet.bean.CardWalletInfo;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.db.CardDao;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.util.TCStringUtil;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.bean.CardBean.CARD_TYPE_COMMON;
import static com.pansoft.openplanet.bean.CardBean.CARD_TYPE_GOLD;
import static com.pansoft.openplanet.bean.CardBean.CARD_TYPE_PLATINUM;
import static com.pansoft.openplanet.bean.CardBean.CARD_TYPE_STAR;

/**
 * 新界面卡片
 *
 * @author will
 */
public class NewAssetCardsFragment extends BaseFragment implements View.OnClickListener {
    //
    private View rootView;
    private ImageView tvNewCard;
    private ViewPager viewpager;
    private TextView tvCurrentPage;
    private TextView tvTotalPage;
    private LinearLayout llNoCards;
    private LinearLayout llPage;
    private ImageView ivAdd, ivBuy;
    /**
     * 适配器的数据源
     */
    private int[] drawables;
    private List<CardBean> cardBeanList = new ArrayList<>();
    private CardPagerAdapter cardPagerAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.new_asset_fragment_cards, container, false);
        initView();
        initData();
        initListener();
        return rootView;
    }

    private void initView() {
        tvCurrentPage = rootView.findViewById(R.id.tv_current_page);
        tvTotalPage = rootView.findViewById(R.id.tv_total_page);
        tvNewCard = rootView.findViewById(R.id.tv_new_card);
        llNoCards = rootView.findViewById(R.id.ll_no_cards);
        viewpager = rootView.findViewById(R.id.viewpager);
        llPage = rootView.findViewById(R.id.ll_page);
        ivAdd = rootView.findViewById(R.id.iv_add);
        ivBuy = rootView.findViewById(R.id.iv_buy);
        ivAdd.setOnClickListener(this);
        ivBuy.setOnClickListener(this);
        tvNewCard.setOnClickListener(this);
        llNoCards.setOnClickListener(this);
        drawables = new int[]{R.drawable.asset_card_common, R.drawable.asset_card_gold,
                R.drawable.asset_card_platium, R.drawable.asset_card_ip};
    }

    public void refresh() {
        refreshData();
    }


    private void initData() {

        cardBeanList = new CardDao(getActivity()).getCardBeanList();

        getCardsInfo();

    }

    /**
     * 刷新数据，重新从数据库读取
     */
    private void refreshData() {
        cardBeanList = new CardDao(getActivity()).getCardBeanList();

        if (cardBeanList.size() == 0) {
            setShowErrorLayout();
        }
        setShowViewPagerLayout();
        cardPagerAdapter = new CardPagerAdapter(getActivity(), drawables, cardBeanList);
        viewpager.setAdapter(cardPagerAdapter);
    }

    /**
     * 从服务器请求数据，并与本地数据库比对，缺少则加入数据库
     * 对于本地数据库多的，暂不做处理
     */
    private void getCardsInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("mainAccountAddress", EnvironmentVariable.getProperty("tc_ethAddress"));
        TCRequestUtil.getCommonRequest(TAG, "card/findCardsByMainAccountAddress", map,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if ("success".equals(jsonObject.optString("result"))) {
                                JSONArray jsonArray = jsonObject.optJSONArray("cardsInfo");
                                if (jsonArray.length() > cardBeanList.size()) {
                                    //本地存储的卡片和服务器的不一致，只处理服务器多的,不删除本地多的
                                    //防止在本地创建了冷钱包，但是服务器没有存上这种情况
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject cardObject = jsonArray.getJSONObject(i);
                                        //卡号
                                        String cardId = cardObject.optString("id");
                                        for (int j = 0; j < cardBeanList.size(); j++) {
                                            if (cardId.equals(cardBeanList.get(j).getUid())) {
                                                //卡号一致，不处理
                                                break;
                                            }
                                        }
                                        //没有一致的卡号，说明本地没有，那么加入数据库
                                        CardBean cardBean = new CardBean();
                                        cardBean.setUid(cardId);
                                        //cardInfo
                                        String cardInfo = cardObject.optString("cardInfo");
                                        if (!StringUtils.isEmpty(cardInfo)) {
                                            JSONObject infoObject = new JSONObject(cardInfo);
                                            String version = infoObject.optString("v");
                                            //读取钱包位置
                                            String[] rawPositions = jsonObject.optString("p").split(",");
                                            cardBean.setVersion(version);
                                        } else {
                                            cardBean.setVersion("0");
                                        }

                                        cardBean.setCardType(cardId.substring(2, 4).replaceAll("^(0+)", ""));


                                        JSONArray walletArray = cardObject.optJSONArray("userColdWallets");
                                        List<CardWalletInfo> cardWalletInfos = new ArrayList<>();
                                        AccountDao accountDao = new AccountDao(getActivity());
                                        for (int j = 0; j < walletArray.length(); j++) {
                                            JSONObject walletObject = walletArray.optJSONObject(j);
                                            CardWalletInfo cardWalletInfo = new CardWalletInfo();
                                            cardWalletInfo.setWalletAvatar(walletObject.optString("accountIcon"));
                                            cardWalletInfo.setWalletName(walletObject.optString("accountName"));
                                            cardWalletInfo.setAddress(walletObject.optString("accountAddress"));
                                            cardWalletInfo.setChainId(walletObject.optInt("blockchainId"));
                                            cardWalletInfo.setInCardPosition(walletObject.optInt("index"));
                                            cardWalletInfos.add(cardWalletInfo);
                                            Account account = accountDao.getAccount(cardWalletInfo.getAddress());
                                            if (account == null) {
                                                //不存在加入
                                                account = new Account();
                                                account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress"));
                                                account.setColdWalletCardUid(cardId);
                                                account.setAddress(cardWalletInfo.getAddress());
                                                account.setAccountType(Account.ACCOUNT_TYPE_COLD);
                                                account.setEnable(true);
                                                account.setAccountAvatar(cardWalletInfo.getWalletAvatar());
                                                account.setAcccountName(cardWalletInfo.getWalletName());
                                                account.setBlockChainName(cardWalletInfo.getChainId() == IPAssetsConstant.CHAIN_ID_ETH ?
                                                        IPAssetsConstant.ChainEnum.ETH.chainName :
                                                        IPAssetsConstant.ChainEnum.BTC.chainName);
                                                accountDao.insertOrReplace(account);
                                            }
                                        }
                                        cardBean.setWalletInfoList(cardWalletInfos);
                                        cardBean.setEnable(true);
                                        new CardDao(getActivity()).insertOrReplace(cardBean);
                                    }
                                } else {
                                    //遍历钱包，若version不一致，则替换
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject cardObject = jsonArray.getJSONObject(i);
                                        //卡号
                                        String cardId = cardObject.optString("id");
                                        CardBean cardBean = new CardBean();
                                        for (int j = 0; j < cardBeanList.size(); j++) {
                                            if (cardId.equals(cardBeanList.get(j).getUid())) {
                                                //卡号一致，不处理
                                                cardBean = cardBeanList.get(i);
                                            }
                                        }

                                        //cardInfo
                                        String cardInfo = cardObject.optString("cardInfo");
                                        if (!StringUtils.isEmpty(cardInfo)) {
                                            JSONObject infoObject = new JSONObject(cardInfo);
                                            String version = infoObject.optString("v");
                                            //读取钱包位置
                                            String[] rawPositions = jsonObject.optString("p").split(",");
                                            if (!StringUtils.isEmpty(cardBean.getVersion()) && !version.equals(cardBean.getVersion())) {
                                                //更新数据库
                                                cardBean.setVersion(version);
                                                JSONArray walletArray = cardObject.optJSONArray("userColdWallets");
                                                List<CardWalletInfo> cardWalletInfos = new ArrayList<>();
                                                AccountDao accountDao = new AccountDao(getActivity());
                                                for (int j = 0; j < walletArray.length(); j++) {
                                                    JSONObject walletObject = walletArray.optJSONObject(j);
//                                                List<CardWalletInfo> cardWalletInfos1 = cardBean.getWalletInfoList();
//                                                for (int k = 0; k < cardWalletInfos1.size(); k++) {
//                                                    if (cardWalletInfos1.get(i).getAddress().equals(walletObject
//                                                            .optString("accountAddress"))) {
//                                                        return;
//                                                    }
//                                                }
                                                    CardWalletInfo cardWalletInfo = new CardWalletInfo();
                                                    cardWalletInfo.setWalletAvatar(walletObject.optString("accountIcon"));
                                                    cardWalletInfo.setWalletName(walletObject.optString("accountName"));
                                                    cardWalletInfo.setAddress(walletObject.optString("accountAddress"));
                                                    cardWalletInfo.setChainId(walletObject.optInt("blockchainId"));
                                                    cardWalletInfo.setInCardPosition(walletObject.optInt("index"));
                                                    cardWalletInfos.add(cardWalletInfo);
                                                    Account account = accountDao.getAccount(cardWalletInfo.getAddress());
                                                    if (account == null) {
                                                        //不存在加入
                                                        account = new Account();
                                                        account.setMainAccoutAddress(EnvironmentVariable.getProperty("tc_ethAddress"));
                                                        account.setColdWalletCardUid(cardId);
                                                        account.setAddress(cardWalletInfo.getAddress());
                                                        account.setAccountType(Account.ACCOUNT_TYPE_COLD);
                                                        account.setEnable(true);
                                                        account.setAccountAvatar(cardWalletInfo.getWalletAvatar());
                                                        account.setAcccountName(cardWalletInfo.getWalletName());
                                                        account.setBlockChainName(cardWalletInfo.getChainId() == IPAssetsConstant.CHAIN_ID_ETH ?
                                                                IPAssetsConstant.ChainEnum.ETH.chainName :
                                                                IPAssetsConstant.ChainEnum.BTC.chainName);
                                                        accountDao.insertOrReplace(account);
                                                    }
                                                }
                                                cardBean.setWalletInfoList(cardWalletInfos);
                                                cardBean.setEnable(true);

                                                new CardDao(getActivity()).insertOrReplace(cardBean);
                                            }
                                        }
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        refreshData();
                    }

                    @Override
                    public void onFail(String error) {
                        refreshData();
                    }
                });
    }

    /**
     * 没有卡片数据时，显示没有卡片的界面布局
     */
    private void setShowErrorLayout() {
        viewpager.setVisibility(View.GONE);
        llNoCards.setVisibility(View.VISIBLE);
        llPage.setVisibility(View.GONE);
        tvNewCard.setVisibility(View.GONE);
    }

    /**
     * 有卡片数据时，显示viewpager的界面布局
     */
    private void setShowViewPagerLayout() {
        llNoCards.setVisibility(View.GONE);
        viewpager.setVisibility(View.VISIBLE);
        llPage.setVisibility(View.VISIBLE);
        tvNewCard.setVisibility(View.VISIBLE);
        //
        tvCurrentPage.setText("1");
        tvTotalPage.setText(String.valueOf(cardBeanList.size()));
        if (cardBeanList.size() == 0) {
            tvCurrentPage.setText("0");
        }
        //
        viewpager.setPageMargin(SizeUtils.dp2px(12));
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == cardBeanList.size()) {
                    tvCurrentPage.setText("-");
                    tvTotalPage.setText("-");
                } else {
                    tvCurrentPage.setText(position + 1 + "");
                    tvTotalPage.setText(cardBeanList.size() + "");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View view) {
        //点击全部按钮跳转到卡片列表界面
        if (view.getId() == R.id.tv_new_card) {
            NewStackActivity.start(_mActivity);
        } else if (view.getId() == R.id.ll_no_cards) {
            //todo 点击加载失败按钮跳转到添加卡片的界面

        } else if (view.getId() == R.id.iv_add) {
            //添加已有卡片的点击事件
            if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                return;
            }
            // 直接读取NFC
            if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(getActivity())) {
                MifareAddCardActivity.start(getActivity());
                //蓝牙读卡器
            } else {
                BleBlutoothScanActivity.start(getActivity(),
                    BleBlutoothScanActivity.TYPE_ADD_CARD, BleBlutoothScanActivity.BLE_TYPE_NFC);
            }
        } else if (view.getId() == R.id.iv_buy) {
            //购买卡片的点击事件
        }
    }

    private static class CardPagerAdapter extends PagerAdapter {

        private Context context;
        private List<CardBean> cardBeanList;

        public CardPagerAdapter(Context context, int[] drawables, List<CardBean> cardBeanList) {
            this.context = context;
            this.cardBeanList = cardBeanList;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            View view = null;
            int addPosition = cardBeanList.size() - 1;
            //最后添加布局的判断
            if (position > addPosition) {
                view = View.inflate(context, R.layout.assets_include_new_add_cards_layout, null);
                addLayoutListener(view);
                container.addView(view);
            } else {
                view = View.inflate(context, R.layout.new_asset_item_card, null);
                ImageView ivIcon = view.findViewById(R.id.iv_bg);
                TextView tvCardType = view.findViewById(R.id.tv_card_type);
                final TextView tvCardNumber = view.findViewById(R.id.tv_card_number);
                TextView tvCardAmount = view.findViewById(R.id.tv_card_amount);
                //
                final CardBean cardBean = cardBeanList.get(position);
                tvCardType.setText(CardBean.getCardTypeName(cardBean.getCardType()));
                tvCardNumber.setText(cardBean.getUid());
                tvCardAmount.setText(String.valueOf(cardBean.getWalletInfoList().size()));
                ivIcon.setImageDrawable(getCardTypeBackgroundDrawable(context, cardBean.getCardType()));
                tvCardNumber.setText(TCStringUtil.formatCardNoHide(cardBean.getUid()));
                //跳转到卡包详情界面
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        NewAssetCardsDetailsActivity.start(context, cardBeanList.get(position).getUid());
                    }
                });
                container.addView(view);
            }

            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            //数据长度加1 最后添加卡片布局
            return cardBeanList.size() + 1;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        /**
         * 添加布局的点击事件
         *
         * @param view
         */
        private void addLayoutListener(View view) {
            ImageView iv_add = view.findViewById(R.id.iv_add);
            ImageView iv_buy = view.findViewById(R.id.iv_buy);
            //添加已有卡片的点击事件
            iv_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 直接读取NFC
                    if (!EnvSupportManager.isSupportNfcWallet() && !EnvSupportManager.isSupportForceBleNfc()) {
                        return;
                    }
                    // 直接读取NFC
                    if (!EnvSupportManager.isSupportForceBleNfc() && Common.hasMifareClassicSupport(context)) {
                        MifareAddCardActivity.start(context);
                        //蓝牙读卡器
                    } else {
                        BleBlutoothScanActivity.start(context,
                                BleBlutoothScanActivity.TYPE_ADD_CARD, BleBlutoothScanActivity.BLE_TYPE_NFC);
                    }
                }
            });
            //购买卡片的点击事件
            iv_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
        }
    }

    /**
     * 获取卡片背景图
     */
    public static Drawable getCardTypeBackgroundDrawable(Context context, String cardType) {
        if ("".equals(cardType) || CARD_TYPE_COMMON.equals(cardType)) {
            return context.getResources().getDrawable(R.drawable.asset_card_common);
        }
        if (CARD_TYPE_GOLD.equals(cardType)) {
            return context.getResources().getDrawable(R.drawable.asset_card_gold);
        }
        if (CARD_TYPE_PLATINUM.equals(cardType)) {
            return context.getResources().getDrawable(R.drawable.asset_card_platium);
        }
        if (CARD_TYPE_STAR.equals(cardType)) {
            return context.getResources().getDrawable(R.drawable.asset_card_ip);
        }
        return context.getResources().getDrawable(R.drawable.asset_card_common);
    }
}
